

const { ethers } = require("hardhat");
const {expect} = require("chai");

console.log("ethers version:", ethers.version);
let MyNFTContract;

describe("MyNFT Contract", function () {

    this.beforeEach(async function () {
        [owner, addr1, addr2, ...addrs] = await ethers.getSigners();

       const MyNFT = await ethers.getContractFactory("MyNFT");
       MyNFTContract = await MyNFT.deploy();
   

       expect(await MyNFTContract.getAddress()).to.properAddress;
    });

    it("mint nft", async function () {

        console.log("Owner address:", await MyNFTContract.getAddress());
        await MyNFTContract.mintNFT(addr1);

        expect(await MyNFTContract.balanceOf(addr1)).to.equal(1);
    });

    it("transfer nft",async function(){
        console.log("Owner address:", await MyNFTContract.getAddress());
       const tx= await MyNFTContract.mintNFT(addr1);

       const receipt = await tx.wait();
 console.log("receipt:",JSON.stringify(receipt,null,2));
//        const transferEvents = await MyNFTContract.queryFilter(MyNFTContract.filters.Transfer(null, null, null),receipt.blockNumber,receipt.blockNumber);
//          console.log("transferEvents:",JSON.stringify(transferEvents,null,2));

// const tokenId = transferEvents[0].args.tokenId;
const event =getEventByABI(receipt)
console.log("tokenId:",event.args.tokenId);
    //    const event = receipt.events?.find(e=>e.event === "Transfer");
    //    const tokenId = event?.args?.tokeId;
    //    console.log("tokenId:",tokenId);

    //     await MyNFTContract.connect(addr1).safeTransferFrom(addr1,owner, tokenId);

    //     expect(await MyNFTContract.balanceOf(owner)).to.equal(1);
    //     expect(await MyNFTContract.balanceOf(addr1)).to.equal(0);
    })
function getEventByABI(receipt) {
    const eventName = "Transfer(address indexed from, address indexed to, uint256 tokenId)";
    const eventSign = ethers.keccak256(ethers.toUtf8Bytes(eventName));

    for (const log of receipt.logs) {
        // 确保是当前合约发出的事件 + 事件签名匹配
        if (
            log.address.toLowerCase() === MyNFTContract.address.toLowerCase() &&
            log.topics[0] === eventSign
        ) {
            try {
                const iface = new ethers.Interface([`event ${eventName}`]);
                const parsed = iface.parseLog(log);

                return parsed;
            } catch (e) {
                console.error("Failed to parse log:", e);
                continue;
            }
        }
    }

    throw new Error(`Event ${eventName} not found in receipt`);
}

    function getEventByFilter(filter,receipt){
        return MyNFTContract.queryFilter(filter,receipt.blockNumber,receipt.blockNumber);
    }
});